import {
  Button,
  Col,
  ConfigProvider,
  Dropdown,
  Form,
  Input,
  Menu,
  Modal,
  Popconfirm,
  Row,
  Space,
  Table
} from 'antd';
import React, { useRef, useState } from 'react';
import http from '@/services/request';
import { DataType } from '@/base-ui/table-Data/tableData';
import zhCN from 'antd/es/locale/zh_CN';
const NewForm = (props: any) => {
  return (
    <Form ref={props.newref} layout={'vertical'} style={{ minHeight: '100%', flex: 1, overflow: 'auto', width: '100%', overflowX: 'hidden' }}>
      <Row >
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 4 }}>
      <Form.Item
        label="请输入批次"
        name="batch"
        rules={[{ required: true, message: '请输入批次' }]}
      >
        <Input></Input>
      </Form.Item>
      <Form.Item
        name="breed"
        label="请输入品种"
        rules={[{ required: true, message: '请输入品种' }]}
      >
        <Input></Input>
      </Form.Item>
      <Form.Item
        label="请输入等级"
        name="grade"
        rules={[{ required: true, message: '请输入等级' }]}
      >
        <Input></Input>
      </Form.Item>
        </Col>
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 4 }}>
      <Form.Item
        label="请输入数量"
        name="number"
        rules={[{ required: true, message: '请输入数量' }]}
      >
        <Input></Input>
      </Form.Item>
      <Form.Item
        name="weight"
        label="请输入重量"
        rules={[{ required: true, message: '请输入货物重量' }]}
      >
        <Input></Input>
      </Form.Item>
      <Form.Item
        name="specification"
        label="请输入规格"
        rules={[{ required: true, message: '请输入规格' }]}
      >
        <Input></Input>
      </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};
function RepoAntd(props: { dataSource: any }) {
  //更多功能定位id
  // const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  // const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);

  //是否新增
  const [edited, setedited]: any = useState(null);
  //高级检索
  const newref: any = useRef();
  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);
  const { dataSource } = props;
  //复选框
  const rowSelection = {
   onChange: (selectedRowKeys: React.Key[]) => {
      setItemSelected(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };
  //table的数据名
  const FormColumns: any = [
    {
      title: '仓库号码',
      dataIndex: 'repositoryId',
      key: 'repositoryId',
      width: 150
    },
    {
      title: '仓储货物名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 150
    },
    {
      title: '产品号码',
      dataIndex: 'productId',
      key: 'productId',
      width: 150
    },
    {
      title: '等级',
      dataIndex: 'grade',
      key: 'grade',
      width: 150
    },
    {
      title: '仓储数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => {}}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            // cancelButtonProps={{ size: 'middle' }}
            onConfirm={() => {
              http
                .delete(`/server/weightSlaughter/delete/${record.id}`)
                .then((res) => {});
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];
  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button type="primary" onClick={(e) => {}}>
              详情
            </Button>
          )
        },
        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        },
        {
          key: 3,
          label: (
            <Button
              onClick={() => {}}
              style={{ backgroundColor: 'yellowGreen' }}
            >
              出库
            </Button>
          )
        }
      ]}
    />
  );
  //按钮组
  const Buttongroup = (props: any) => {
    return (
      <div style={{ marginBottom: 10, float: 'left' }}>
        <Button
          type="primary"
          onClick={() => props.add()}
          style={{ marginRight: 10 }}
        >
          入库
        </Button>
        <Button
          danger
          onClick={() => {
            props.checkIt();
          }}
          style={{ marginRight: 10 }}
        >
          批量出库
        </Button>
      </div>
    );
  };
  const checkIt = () => {
    http({
      url: `/server/dailySlaughter/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then((res) => {
      http.get('/server/dailySlaughter/list/1/10').then((res) => {});
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };
  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/server/dailySlaughter/update/${edited.id}`, {
          ...newedited
        })
        .then((res) => {
          // 再请求一次获得修改后的数据
          http.get('/server/dailySlaughter/list/1/10').then((res) => {});
        });
      setedited(null);
      return;
    }
    //id不在--就是新增
    // handleAddModalOk
    // customerName numberOfPieces only weight averageWeight pickupDate pickupPerson species remark

    const measurement = newref.current.getFieldsValue();

    http
      .post('/server/dailySlaughter/save', {
        ...measurement
      })
      .then((res) => {
        http.get('/server/dailySlaughter/list/1/10').then((res) => {});
      });
  };

  //编辑
  // const edit = (id: any) => {
  //   setAddModalVisible(true);

  //   //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
  //   setTimeout(() => {
  //     newref.current.setFieldsValue({
  //       ...id
  //     });
  //     setedited(id);
  //   }, 0);
  // };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    setTimeout(() => {
      setTimeout(() => {
        newref.current.setFieldsValue({
          batch: '',
          breed: '',
          grade: '',
          number: '',
          weight: '',
          specification: ''
        });
      }, 0);
    });
    setAddModalVisible(true);
  };

  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => {},
      //自定义每页显示项目的选项
      pageSizeOptions: ['1', '2', '3', '4', '5', '6', '8', '10'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => {},
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => {}
    }
  };
  return (
    <div>
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
        exported={() => exported()}
      ></Buttongroup>
      <ConfigProvider locale={zhCN}>
        <Table
          columns={FormColumns}
          dataSource={dataSource}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(dataSource) => dataSource.id}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
        ></Table>
      </ConfigProvider>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse',

        }}
        title="增加入库"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref}></NewForm>
      </Modal>
    </div>
  );
}
export default RepoAntd;
